﻿CREATE FUNCTION PaymentByAPR(
@AmountFinanced money,
@PaymentStart money,
@LoanTerm int,
@ContractDate datetime,
@FirstPaymentDate datetime,
@PaymentsPerYear int,
@DayCountConventionID int,
@NumberOfPayments int,
@APROverride money
)RETURNS numeric(18,2) AS BEGIN

IF @AmountFinanced > 0 AND @PaymentStart > 0 AND @LoanTerm > 0 AND @PaymentsPerYear > 0 AND
	 @NumberOfPayments > 0 AND @APROverride > 0
BEGIN
DECLARE @APR money SET @APR = dbo.RATExByAfPmt(@AmountFinanced, @PaymentStart, @LoanTerm, @ContractDate, @FirstPaymentDate,
@PaymentsPerYear, @DayCountConventionID) * 100
WHILE @APR < @APROverride BEGIN
	SET @PaymentStart = @PaymentStart + 1
	SET @APR = dbo.RATExByAfPmt(@AmountFinanced, @PaymentStart, @LoanTerm, @ContractDate,
			@FirstPaymentDate, @PaymentsPerYear, @DayCountConventionID) * 100
END
WHILE @APR > @APROverride BEGIN
	SET @PaymentStart = @PaymentStart - .1
	SET @APR = dbo.RATExByAfPmt(@AmountFinanced, @PaymentStart, @LoanTerm, @ContractDate,
			@FirstPaymentDate, @PaymentsPerYear, @DayCountConventionID) * 100
END
WHILE @APR < @APROverride BEGIN
	SET @PaymentStart = @PaymentStart + .01
	SET @APR = dbo.RATExByAfPmt(@AmountFinanced, @PaymentStart, @LoanTerm, @ContractDate,
			@FirstPaymentDate, @PaymentsPerYear, @DayCountConventionID) * 100
END

RETURN @PaymentStart
END

RETURN NULL
END


